<?php

class SiteController extends BackOfficeController
{
    public function init()
    {
        if (!Yii::app()->authManager->isAssigned('administrators', Yii::app()->user->id))
            throw new CHttpException(403,Yii::t('yii','You are not authorized to perform this action.'));
        parent::init();
    }
    
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
        $this->actionUpdate();
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate()
	{
        if (Yii::app()->request->IsPostRequest) {
            // save posted data
            $_POST['validateOnly'] = ($this->post('ajax','') == 'site-form');
            $result = FSM::run('Cms.Site.save', $_POST);
            $model = $result->model;

            if ($this->post('ajax','') == 'site-form'){
                echo $result->getActiveErrorMessages($result->model);
                Yii::app()->end();
            }   
            if (! $result->hasErrors()) {
                $this->message = Yii::t('Core','Item has been saved successfully.');
                $this->redirect(array('update', 'id'=>$model->id));
            }
        } else {
            // show edit form
            $id = $this->get('id', 0);
            if ($id) {
                $result = FSM::run('Cms.Site.get', array('id' => $id));
                if (!$result->hasErrors())
                    $model = $result->model;
            }
            if (!isset($model) || !is_object($model))
                $model = new Site();
        }
            
        $this->render('update', array('model' => $model));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete()
	{
        if(Yii::app()->request->isPostRequest)
        {
            // we only allow deletion via POST request
            if (($id = $this->get('id',null)) !== null) {
                $ids = is_numeric($id) ? array($id) : explode(',',$id);
                
                // delete one or multiple objects given the list of object IDs
                $result = FSM::run('Cms.Site.delete', array('ids' => $ids));
                if ($result->hasErrors()) {
                    echo $result->getError('ErrorCode');
                } elseif(!Yii::app()->request->isAjaxRequest) {
                    // only redirect user to the admin page if it is not an AJAX request
                    $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
                }
            } else {
                throw new CHttpException(400,Yii::t('Core','Cannot delete item with the given ID.'));
            }
        } else {
            throw new CHttpException(400,Yii::t('Core','Invalid request. Please do not repeat this request again.'));
        }
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
        $this->actionAdmin();
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
        $model=new Site('search');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['Site']))
            $model->attributes=$_GET['Site'];

        $this->render('admin',array(
            'model'=>$model,
        ));
	}
    
    public function actionStatusUrl()
    {
        $result = FSM::run('Cms.SiteUrl.changeStatus', $_GET);
        echo $result->toJson();
    }
    
    public function actionStatus()
    {
        $result = FSM::run('Cms.Site.changeStatus', $_GET);
        echo $result->toJson();
    }
    
    public function actionSetDefault($id)
    {
        $result = FSM::run('Cms.Site.setDefault', $_GET);
        echo $result->toJson();
    }
    
    public function actionSetDefaultUrl($id)
    {
        $result = FSM::run('Cms.SiteUrl.setDefault', $_GET);
        echo $result->toJson();
    }
    
    public function actionUrl($site_id)
    {
        $model=new SiteUrl('search');
        $model->unsetAttributes();  // clear any default values
        $model->site_id = $site_id;
        if(isset($_GET['SiteUrl']))
            $model->attributes=$_GET['SiteUrl'];

        $html = $this->renderPartial('/admin/siteUrl/admin',array(
            'model'=>$model,
            'siteId'=>$site_id,
        ), true, true);
        $html = preg_replace('/<link rel="stylesheet" type="text\/css" href="([^"]+)\.css" \/>/', '', $html);
        $html = preg_replace('/<script type="text\/javascript" src="([^"]+)\.js"><\/script>/', '', $html);
        echo $html;
    }
    
    public function actionAddUrl($site_id)
    {
        $this->actionUpdateUrl($site_id);
    }
    
    public function actionUpdateUrl($site_id)
    {
        if (Yii::app()->request->IsPostRequest) {
            // save posted data
            $_POST['validateOnly'] = ($this->post('ajax','') == 'siteUrl-form');
            $result = FSM::run('Cms.SiteUrl.save', $_POST);
            $model = $result->model;

            if ($this->post('ajax','') == 'siteUrl-form'){
                echo $result->getActiveErrorMessages($result->model);
                Yii::app()->end();
            }   
            if (! $result->hasErrors()) {
                //$this->message = Yii::t('Core','Item has been saved successfully.');
                $script = "parent.\$.reloadSiteUrlTab();parent.\$.fancybox.close();";
                Yii::app()->clientScript->registerScript(__CLASS__.'#ReloadSiteUrl', $script, CClientScript::POS_READY);
            }
        } else {
            // show edit form
            $id = $this->get('id', 0);
            if ($id == 0) {
                $model = new SiteUrl();
            } else {
                $model = FSM::run('Cms.SiteUrl.get', array('id' => $id))->model;
            }
            $model->site_id = $site_id;
        }
        
        $this->render('/admin/siteUrl/update', array('model' => $model));
    }
}
